import http from "@/http";
import { BudgetSheet, BudgetSheetQuery, BudgetSheetCreateDTO, BudgetSheetUpdateDTO, HistoricalBudgetSheetSaveDTO, BudgetDetailReport, BudgetDetailReportQuery } from './type';

// 分页查询预算单列表
export const getBudgetSheetListApi = (params: BudgetSheetQuery) => {
  return http.get("/budgetSheet/queryBudgetSheetList", params);
};

// 根据ID获取预算单详情
export const getBudgetSheetDetailApi = (id: number | string) => {
  return http.get(`/budgetSheet/getBudgetSheetDetail/${id}`);
};

// 根据ID获取预算单详情
export const getBudgetSheetDetailAllApi = (id: number | string) => {
  return http.get(`/budgetSheet/getBudgetSheetDetailAll/${id}`);
};

// 预览预算单详情（发送表单数据）
export const getBudgetSheetDetailPreviewApi = (data: BudgetSheet) => {
  return http.post("/budgetSheet/getBudgetSheetDetailPreview", data);
};

// 新增预算单
export const addBudgetSheetApi = (data: BudgetSheetCreateDTO) => {
  return http.post("/budgetSheet/addBudgetSheet", data);
};

// 更新预算单
export const updateBudgetSheetApi = (data: BudgetSheetUpdateDTO) => {
  return http.put("/budgetSheet/updateBudgetSheet", data);
};

// 删除预算单
export const deleteBudgetSheetApi = (id: number | string) => {
  return http.delete(`/budgetSheet/deleteBudgetSheet/${id}`);
};

// 保存历史预算单
export const saveHistoricalBudgetSheetApi = (data: HistoricalBudgetSheetSaveDTO) => {
  return http.post("/historicalQuotation/saveHistoricalBudgetSheet", data);
};

// 导出预算单列表
export const exportBudgetSheetApi = (params?: BudgetSheetQuery) => {
  // 构建查询字符串
  const queryString = params ? new URLSearchParams(
    Object.entries(params).reduce((acc, [key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        acc[key] = String(value);
      }
      return acc;
    }, {} as Record<string, string>)
  ).toString() : '';
  
  const url = `${http['instance'].defaults.baseURL}/budgetSheet/export${queryString ? '?' + queryString : ''}`;
  window.location.href = url;
  return Promise.resolve();
};

// 获取预算明细成本报表
export const getBudgetDetailReportApi = (params: BudgetDetailReportQuery) => {
  return http.get("/budgetDetailReport/getBudgetDetailReport", params);
};

/**
 * 批量复制预算表
 */
export const batchCopyApi = (params: { sourceIds: number[], targetProjectId: number }) => {
  return http.post('/budgetSheet/batchCopy', params);
};